package com.dingwen.treasure.base.context;

import java.util.Objects;

/**
 * 用户变量上下文扩展
 *
 * @author dingwen
 * @date 2022/11/28
 */
public class UserVariableContextExt {

    /**
     * 用户变量
     */
    private static final ThreadLocal<UserVariableContext> USER_VARIABLE_CONTEXT_THREAD_LOCAL = new ThreadLocal<>();


    /**
     * 设置用户名
     *
     * @param userName 用户名
     */
    public static void setUserName(String userName){
        getUserVariableContext().setUserName(userName);
    }


    /**
     * 获得用户名
     *
     * @return {@link String}
     */
    public static String getUserName(){
        UserVariableContext userVariableContext = USER_VARIABLE_CONTEXT_THREAD_LOCAL.get();
        if (Objects.isNull(userVariableContext)){
            return null;
        }
        return userVariableContext.getUserName();
    }
    /**
     * 设置用户id
     *
     * @param userId 用户id
     */
    public static void setUserId(Long userId){
        getUserVariableContext().setUserId(userId);
    }

    /**
     * 获取用户id
     * @return {@link Long}
     */
    public static Long getUserId(){
        UserVariableContext userVariableContext = USER_VARIABLE_CONTEXT_THREAD_LOCAL.get();
        if (Objects.isNull(userVariableContext)){
            return null;
        }
        return userVariableContext.getUserId();
    }


    /**
     * 删除
     */
    public static void remove(){
        USER_VARIABLE_CONTEXT_THREAD_LOCAL.remove();
    }





    /**
     * 得到用户变量上下文
     *
     * @return {@link UserVariableContext}
     */
    private static UserVariableContext getUserVariableContext(){
       UserVariableContext userVariableContext = USER_VARIABLE_CONTEXT_THREAD_LOCAL.get();
       if (Objects.isNull(userVariableContext)) {
           userVariableContext = new UserVariableContext();
           USER_VARIABLE_CONTEXT_THREAD_LOCAL.set(userVariableContext);
       }
       return userVariableContext;
   }
}
